<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Banner extends Admin_Controller
{
    function __construct()
    {
        parent::__construct();
        $this->load->model('banner_m');
    }

    public function index()
    {
        $banner         = $this->banner_m->select();
        $data['banner'] = $banner;
        $this->load->view('banner/index', $data);
    }

    public function add()
    {
        $data['pic_path'] = "[]";
        $data['pic_con']  = json_encode([]);
        $this->load->view('banner/form', $data);
    }

    public function edit($id = null)
    {
        $banner = $this->banner_m->find($id);
        if (!$banner) {
            show_message('参数错误！', site_url(X_URL . 'Banner/index'));
        }
        $del_url          = base_url("index.php/Upload/delete_img?url=" . $banner['pic_url']);
        $pic_con[]        = [
            'caption' => "轮播图",
            'size'    => 576237,
            'width'   => '120px',
            'url'     => $del_url,
            "key"     => $banner['id'],
        ];
        $data['pic_path'] = "['" . $banner['pic_url'] . "']";
        $data['pic_con']  = json_encode($pic_con);
        $data['banner']   = $banner;

        $this->load->view('banner/form', $data);
    }

    public function del($type_id)
    {
        if ($type_id) {
            if ($this->banner_m->delete($type_id)) {
                show_message('恭喜，删除成功！', site_url(X_URL . 'Banner/index'), 1);
            } else {
                show_message('参数错误！', site_url(X_URL . 'Banner/index'));
            }
        } else {
            $this->error('参数错误！');
        }
    }

    public function update()
    {
        $post            = $this->input->post();
        $data['title']   = $post['title'];
        $data['pic_url'] = $post['pic_url'] ?? "#";
        $data['link']    = $post['link'] ?? "#";
        $data['type']    = $post['type'] ?? 0;
        $id              = $post['id'] ?? 0;
        if ($data['title'] == '') {
            show_message('名称不能为空！', site_url(X_URL . 'Banner/index'));
        }
        if (!$id) {
            $this->banner_m->insert($data);
        } else {
            $this->banner_m->update(['id' => $id], $data);
        }
        show_message('恭喜，操作成功！', site_url(X_URL . 'Banner/index'), 1);
    }
}

